

--To create the flight plans in the mission file for all flights in the ATO
--Initiated by Main_NextMission.lua
------------------------------------------------------------------------------------------------------- 
-- Miguel Fichier Revision M08.g__M12
------------------------------------------------------------------------------------------------------- 
-- Miguel21 modification M12 : Skill
-- Miguel21 modification M11.ic : Multiplayer
-- Miguel21 modification M08.g : départ de la piste + debug hotstart + intercepteur CVN
-- Miguel21 modification M06 : helicoptere playable
-- Miguel21 modification M03.c : Parking assigné des AV8 sur LHA + CVN Apparition décalé, LHA et FARP + E-2C S-3B + Apparition retardé
-- Miguel21 modification M02 : Ajout TACAN
-- Miguel21 modification M01 : ajout datalink
------------------------------------------------------------------------------------------------------- 

debugLoc = false
	
	-- init multiplayer variable
	MultiPlayerFlight1 = false
	MultiPlayerFlight2 = false
	-- packPlayer = false
	tabCallSign = {}
	numCallSign = {}
	deltaH = 0
	
----- function to create callsigns for aircraft in ATO -----
local callsign_west = {
	generic = {
		[1] = "Enfield",
		[2] = "Springfield",
		[3] = "Uzi",
		[4] = "Colt",
		[5] = "Dodge",
		[6] = "Ford",
		[7] = "Chevy",
		[8] = "Pontiac",
	},
	AWACS = {
		[1] = "Overlord",
		[2] = "Magic",
		[3] = "Wizard",
		[4] = "Focus",
		[5] = "Darkstar",
	},
	tanker = {
		[1] = "Texaco",
		[2] = "Arco",
		[3] = "Shell",
	}

}

 placePA = {}
				
 -- placePA = {
				-- [1]= { 
				      -- ["hot"] = {},
				      -- },
				-- [2] = {
					  -- ["hot"] = {},
					  -- },
				-- [3] = { 
					  -- ["hot"] = {},
					  -- },
				-- [4] = { 
					  -- ["hot"] = {},
					  -- }
				-- }

local callsign_west_counter = {
	generic = math.random(0, #callsign_west.generic - 1),
	AWACS = math.random(0, #callsign_west.AWACS - 1),
	tanker = math.random(0, #callsign_west.tanker - 1),
}
local callsign_east_counter = 0

local function GetCallsign(country, flight_n, aircraft_n, task)

	-- ['callsign'] = {
		-- [1] = 4,
		-- [2] = 1,
		-- [3] = 1,
		-- ['name'] = 'Colt11',
	-- }

	local style
	if country == "Belgium" or country == "UK" or country == "Georgia" or country == "Denmark" or country == "Israel" or country == "Spain" or country == "Canada" or country == "Norway" or country == "USA" or country == "Turkey" or country == "France" or country == "The Netherlands" or country == "Italy" or country == "Australia" or country == "South Korea" or country == "Croatia" or country == "USAF Aggressors" or country == "Sweden" then
		style = "west"
	else
		style = "east"
	end
	
	local callsign
	if style == "west" then
		local category
		if task == "AWACS" then
			category = "AWACS"
		elseif task == "Refueling" then
			category = "tanker"
		else
			category = "generic"
		end
	
		if flight_n == 1 and aircraft_n == 1 then
			callsign_west_counter[category] = callsign_west_counter[category] + 1
			if callsign_west_counter[category] > #callsign_west[category] then
				callsign_west_counter[category] = 1
			end
			callsign_flight = math.random(0, 8)
		end
		
		local badTest = false
		local name
		
		if aircraft_n == 1 then
			
			local ir = 1
			repeat
				ir = ir+1
				callsign_flight = callsign_flight + 1
				if callsign_flight > 9 then
					callsign_flight = 1
				end
				
				if ir >20 then
					print("errorCallsign_flight "..callsign_flight)
					_affiche(numCallSign, "numCallSign")
					stopBug = true
					break
				end
				
				if not numCallSign[callsign_west_counter[category]] then 
					numCallSign[callsign_west_counter[category]] = {}
				end
				-- print("PasseCallSign "..callsign_west_counter[category].." // "..callsign_flight.." "..task)
				
			until numCallSign[callsign_west_counter[category]][callsign_flight] ~= true 	
			
		end
			
		numCallSign[callsign_west_counter[category]][callsign_flight] = true
			
		-- modification Miguel21 M11 multijoueur
		_name = callsign_west[category][callsign_west_counter[category]] .. callsign_flight .. aircraft_n
		
		for n , tab in  ipairs(tabCallSign) do
			if tab == _name then
				print("Buuuuuuug CallSign ".. _name)
				_affiche(tabCallSign, "tabCallSign")
				stopBug = true
			end
		end
		
		 table.insert(tabCallSign, _name)
		 
		 
			callsign = {
				[1] = callsign_west_counter[category],
				[2] =  callsign_flight,
				[3] =  aircraft_n,
				name = _name
			}

		
	elseif style == "east" then
		if aircraft_n == 1 then
			callsign_east_counter = callsign_east_counter + 1
		end
		callsign = 90 + callsign_east_counter * 10 + aircraft_n
	end

	return callsign
end


----- function to assign frquencies to packages -----
local assigned_freq = {}														--table to store frequencies in use
local package_freq = {															--table to store frequencies assigned to packages
	["blue"] = {},
	["red"] = {},
}

												--table to store TACAN in use

local function GetFrequency(side, pack_n, helicopter)
	local freq
	if package_freq[side][pack_n] then											--if package already has a frequency
		return package_freq[side][pack_n]										--return frequency
	else																		--packe has no frequency yet
	
  	 if helicopter ~= true then
    		repeat
    			freq = math.random(camp.freq_min, camp.freq_max - 1)				--find random frequency in mHz
    			local deci = math.random(0, 9) / 10									--random first decimal place
    			local mil = math.random(0, 3) * 25 / 100							--random second and third decimal place (00/25/50/75)
    			freq = freq + deci + mil											--combine to complete frequency
    		until assigned_freq[freq] == nil										--repeat until a frequency is found that is not yet in use
     end
 -- modif Miguel21 M06 : helicopter playable    
    	if helicopter == true then
		  repeat
			  freq = math.random(radioMod.freq_heli_min, radioMod.freq_heli_max - 1)        --find random frequency in mHz
			  local deci = math.random(0, 9) / 10                 --random first decimal place
			  local mil = math.random(0, 3) * 25 / 100              --random second and third decimal place (00/25/50/75)
			  freq = freq + deci + mil                      --combine to complete frequency
			until assigned_freq[freq] == nil                    --repeat until a frequency is found that is not yet in use 	
    	end
		
		assigned_freq[freq] = true												--mark frequency in use
		package_freq[side][pack_n] = freq										--store frequency for package
		return freq																--return frequency
	end
end



local assigned_channel = {}
 package_channel = {															--table to store frequencies assigned to packages
	["blue"] = {},
	["red"] = {},
}		


	-- tableTacanFreq = {
		-- [37] = 1124000000, --ok
		-- [53] = 1140000000, --ok
		-- [54] = 1141000000, -- ok
		-- [55] = 1142000000, -- ok
		-- [56] = 1143000000, --ok
		-- [57] = 1144000000, --ok
		-- [58] = 1145000000, --ok
		-- [59] = 1146000000, --ok
		-- [60] = 1147000000, --
		-- [61] = 1148000000, --ok
		-- [62] = 1149000000,  --ok
		-- [63] = 1150000000  --ok
		-- }
		
		-- frequency = (channel + 1087) *1000000

-- modif Miguel M02 : Ajout TACAN

local function GetTacanChannel(side, pack_n, flight, n)									-- MIGUEL21
	local channel

	if not package_channel[side][pack_n] then package_channel[side][pack_n] = {} end
	if not package_channel[side][pack_n][flight] then package_channel[side][pack_n][flight] = {} end
		
	if package_channel[side][pack_n][flight][n] then											--if package already has a channel

		return package_channel[side][pack_n][flight][n]										--return channel
	else																		--packe has no channel yet
		repeat
			channel = math.random(37, 63)				                        --find random channel
			-- channel = math.random(60, 63)				                        --find random channel

		until assigned_channel[channel] == nil										--repeat until a channel is found that is not yet in use
		
		assigned_channel[channel] = true												--mark channel in use
		package_channel[side][pack_n][flight][n] = channel										--store frequency for package

		return channel																--return channel
	end
end



-- modif Miguel M02 : Ajout TACAN 
local assigned_unitId = {}
local package_unitId = {}

local function GetUnitId( country, plane, p, role, f, n)											-- MIGUEL21 // UnitId
	local unitId
	
	
	if not package_unitId[country] then package_unitId[country] = {} end	
	if not package_unitId[country][plane] then package_unitId[country][plane] = {} end	
	if not package_unitId[country][plane][p] then package_unitId[country][plane][p] = {} end
	if not package_unitId[country][plane][p][role] then package_unitId[country][plane][p][role] = {} end
	if not package_unitId[country][plane][p][role][f] then package_unitId[country][plane][p][role][f] = {} end

	if package_unitId[country][plane][p][role][f][n] then
	
		return package_unitId[country][plane][p][role][f][n]
	else

			unitId = GenerateID()
			if assigned_unitId[unitId] then
			
			print("ERRRRRRRRRORRRRRRRRR generation IdPlane")
			
			print(" country"..
			country..
			plane..
			p..
			f..
			n)
			
			stopBug = true
			
			end

		assigned_unitId[unitId] = true
		package_unitId[country][plane][p][role][f][n] = unitId

		return unitId																
	end
end
			
-- afin de debloquer les intercepteurs sur le pont des PA, on les retarde  en activant l'option  ["lateActivation"] = true,			
local function GetStartTime( flight)											-- Miguel21 modification M08.e
		if (flight.type == 'F-14B' or flight.type == 'FA-18C_hornet' ) and flight.player ~= true and string.find(flight.base,"CVN")	and flight.task == "Intercept"	then
-- print("Retard StarTime")
			return 86400
			-- return 0
		else
			return 1
		end

end	
local function GetActivation( flight)											-- Miguel21 modification M08.e
		if (flight.type == 'F-14B' or flight.type == 'FA-18C_hornet' ) and flight.player ~= true and string.find(flight.base,"CVN")	and flight.task == "Intercept"	then
			return true
		else
			return false
		end

end	
----- create flight plans in mission file for all flights in ATO -----
for side, pack in pairs(ATO) do													--iterate through sides in ATO
	for p = 1, #pack do															--iterate through packages in sides
	
		local Pn = 0															--variable to count flights in package
		local nb_flight_type = 0												--variable Miguel21 modification M07.b

		
		for role,flight in pairs(pack[p]) do									--iterate through roles in package (main, SEAD, escort)		
			for f = 1, #flight do												--iterate through flights in roles
			flag_4Place = false
			-- modification Miguel21 M0.2 Apparition décalé sur PA, LHA et FARP
		   if flight[f].base == "Stennis"  or string.find(flight[f].base,"CVN") or string.find(flight[f].base,"LHA")
			 or string.find(flight[f].base,"FARP") then  
			 flag_4Place  = true
		   end 
			
        flight[f].multi2 = false                      --variable Miguel21 modification M11 multijoueur

						
            
				
				Pn = Pn + 1														--count flights in package
				
				local weaponType = 1073741822																			--Weapon types to use (default auto)
				if flight[f].loadout.weaponType == "Cannon" then
					weaponType = 805306368																				--Use cannon only
				elseif flight[f].loadout.weaponType == "Rockets" then
					weaponType = 30720																					--Use rockets only
				elseif flight[f].loadout.weaponType == "Bombs" then
					weaponType = 2032																					--Use unguided bombs only
				elseif flight[f].loadout.weaponType == "Guided bombs" then
					weaponType = 14																						--Use guided bombs only
				elseif flight[f].loadout.weaponType == "ASM" then
					weaponType = 4161536																				--Use ASM only
				end
				
				----- define waypoints -----
				local egress_wp													--local variable to store the Egress WP
				local target_wp_remove											--local variable for the target waypoint to be potentially removed for standoff ground attacks
				local spawn_time												--local variable to store spawn time
				local departure_time											--local variable to store departure time
				local waypoints = {}											--define waypoints of flight
				
				for w = 1, #flight[f].route do
					waypoints[w] = {
						["name"] = flight[f].route[w].id,
						["briefing_name"] = flight[f].route[w].id,				--not needed for actual mission creation, but added for navigation overview in briefing
						["alt"] = flight[f].route[w].alt,
						["type"] = "Turning Point",
						["action"] = "Turning Point",
						["alt_type"] = "BARO",
						["formation_template"] = "",
						["properties"] = 
						{
							["vnav"] = 1,
							["scale"] = 0,
							["angle"] = 0,
							["vangle"] = 0,
							["steer"] = 2,
						},
						["ETA"] = flight[f].route[w].eta,
						["y"] = flight[f].route[w].y,
						["x"] = flight[f].route[w].x,
						["speed"] = pack[p].main[1].loadout.vCruise,
						["ETA_locked"] = true,
						["task"] = 
						{
							["id"] = "ComboTask",
							["params"] = 
							{
								["tasks"] = {}
							},
						},
						["speed_locked"] = false,
					}
					
					--store spawn and departure time for flight
					if flight[f].route[w].id == "Taxi" or flight[f].route[w].id == "Spawn" then
						spawn_time = flight[f].route[w].eta
					elseif flight[f].route[w].id == "Departure" then
						departure_time = flight[f].route[w].eta
					end
					
					--alter departure alt to prevent air spawn collisions of multiple packages -- M6.1 sauf helicopter
					if flight[f].route[w].id == "Departure" and flight[f].helicopter ~= true then
						waypoints[w]["alt"] = waypoints[w]["alt"] + ((p - 1) * 50)
					end

					
					--set attack speed for attack, target and egress waypoints
					if waypoints[w]["name"] == "Attack" or waypoints[w]["name"] == "Target" or waypoints[w]["name"] == "Egress" then
						waypoints[w]["ETA_locked"] = false
						waypoints[w]["speed_locked"] = true
						waypoints[w]["speed"] = pack[p].main[1].loadout.vAttack
					elseif waypoints[w]["name"] == "Join" or waypoints[w]["name"] == "Departure" then
						waypoints[w]["speed"] = pack[p].main[1].loadout.vCruise / 4 * 3										--speed to Join Point is 3/4 cruise speed
					end
					
					--attack waypoint is a fly over point
					if waypoints[w]["name"] == "Attack" then
						waypoints[w]["action"] = "Fly Over Point"
					end
					
					--fighter escorts fly with cruise speed to egress
					if waypoints[w]["name"] == "Egress" and flight[f].task == "Escort" then
						waypoints[w]["speed"] = pack[p].main[1].loadout.vCruise
					end
					
					--set speed locked for all WP after Egress or Station
					if flight[f].route[w].id == "Egress" or flight[f].route[w].id == "Station" and egress_wp == nil then	--find Egress or first Station WP
						egress_wp = w																						--store tgt wp number
					end
					if egress_wp and w > egress_wp then																		--for all WP after target or first station WP
						waypoints[w]["ETA_locked"] = false
						waypoints[w]["speed_locked"] = true
					end
					
					--player flight WP ETA
					if flight[f].player then
						if waypoints[w]["name"] == "Target" or waypoints[w]["name"] == "Station" then
							waypoints[w]["ETA_locked"] = true
							waypoints[w]["speed_locked"] = false
						elseif waypoints[w]["name"] == "Join" then															--ETA of join should be unlocked (so it is no target point for Viggen), but speed needs to be reduced to allow time for start up and take off
							waypoints[w]["ETA_locked"] = false
							waypoints[w]["speed_locked"] = true
							waypoints[w]["speed"] = GetDistance(waypoints[w - 1], waypoints[w]) / waypoints[w]["ETA"]		--exact speed to rach join at required ETA
						else
							waypoints[w]["ETA_locked"] = false
							waypoints[w]["speed_locked"] = true
						end
					end
					
					--altitudes below 1000m are AGL instead of MSL
					if waypoints[w]["alt"] <= 1000 then
						waypoints[w]["alt_type"] = "RADIO"
					end
					
					--take off and landing -- Mod M6 Departure VS taxi
					if flight[f].route[w].id == "Departure" or flight[f].route[w].id == "Intercept" then
						waypoints[w]["type"] = "TakeOffParking"
						waypoints[w]["action"] = "From Parking Area"
						if flight[f].airdromeId > 40 then
							waypoints[w]["linkUnit"] = flight[f].airdromeId
							waypoints[w]["helipadId"] = flight[f].airdromeId
						else
							waypoints[w]["airdromeId"] = flight[f].airdromeId
						end

						
						--if defined in mission_ini, player flight starts with engines running on parking -- Mod_8b
						if flight[f].player == true and mission_ini.parking_hotstart then
						  waypoints[w]["action"] = "From Parking Area Hot"
						  waypoints[w]["type"] = "TakeOffParkingHot"
						end
						
						--if defined in mission_ini, player flight starts with engines running on runway -- Mod_8b
						-- if flight[f].player == true and mission_ini.hotstart then
						  -- waypoints[w]["action"] = "From Runway"
						  -- waypoints[w]["type"] = "TakeOff"
						-- end
							
						--if defined in mission_ini, only with intercept mission, player flight starts with engines running -- Mod_8b 
						if flight[f].player == true and mission_ini.intercept_hotstart == true and flight[f].route[w].id == "Intercept" then
							waypoints[w]["action"] = "From Parking Area Hot"
							waypoints[w]["type"] = "TakeOffParkingHot"
						end
						
						 -- Miguel21 Mod M6, if define in mod_camp.lua,  hotstart on define type aeronef or helicopter
						if  hotstart[flight[f].type]   then                          
						   waypoints[1]["action"] = hotstart[flight[f].type]["action"]
						   waypoints[1]["type"] = hotstart[flight[f].type]["type"]
						end				
						
						
					elseif flight[f].route[w].id == "Land" then
						waypoints[w]["type"] = "Land"
						waypoints[w]["action"] = "Landing"
						if flight[f].airdromeId > 40 then
							waypoints[w]["linkUnit"] = flight[f].airdromeId
							waypoints[w]["helipadId"] = flight[f].airdromeId
						else
							waypoints[w]["airdromeId"] = flight[f].airdromeId
						end
						if flight[f].task == "Nothing" then
							if db_airbases[flight[f].target.destination].airdromeId > 40 then
								waypoints[w]["linkUnit"] = flight[f].airdromeId
								waypoints[w]["helipadId"] = db_airbases[flight[f].target.destination].airdromeId
							else
								waypoints[w]["airdromeId"] = db_airbases[flight[f].target.destination].airdromeId
							end
						end
					end -- end of TAXI/INTERCEPT or LAND
					
					--target WP to be removed for non-player A-G attacks
					if flight[f].route[w].id == "Target" then											--WP is target WP
						if flight[f].task ~= "Reconnaissance" and flight[f].task ~= "Laser Illumination" and (flight[f].task ~= "Strike" or flight[f].target.class ~= "airbase") then		--target WP is removed for all A-G tasks except recon or laser illumination or Strike against airbases (needs to aproach target to search for aircraft on ground)
							if flight[f].player ~= true then											--not the player flight (player always gets a target WP)
								target_wp_remove = w
							end
						end
					end
					
					--formations
					if flight[f].route[w].id == "Departure" or flight[f].route[w].id == "Split" then
						local task_entry = {															--Finger Four Close
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["auto"] = false,
							["id"] = "WrappedAction",
							["enabled"] = true,
							["params"] = 
							{
								["action"] = 
								{
									["id"] = "Option",
									["params"] = 
									{
										["variantIndex"] = 1,
										["name"] = 5,
										["formationIndex"] = 6,
										["value"] = 393217,
									},
								},
							},
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					elseif flight[f].route[w].id == "Join" or flight[f].route[w].id == "Spawn" then
						local task_entry = {															--Spread Four Close
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["auto"] = false,
							["id"] = "WrappedAction",
							["enabled"] = true,
							["params"] = 
							{
								["action"] = 
								{
									["id"] = "Option",
									["params"] = 
									{
										["variantIndex"] = 1,
										["name"] = 5,
										["formationIndex"] = 7,
										["value"] = 458753,
									},
								},
							},
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
	
	-- modif Miguel M01 : ajout datalink
					
					--EPLRS Capacity
                    -- -E-2C
                    -- -E-3A
                    -- -F-15C
                    -- -F-15E
                    -- -F-16C
                    -- -F/A-18C
                    -- -F/A-18C Lot 20

      if flight[f].route[w].id == "Departure" or flight[f].route[w].id == "Split" or flight[f].route[w].id == "Join" or flight[f].route[w].id == "Spawn" then
          if flight[f].type == "E-2C" or flight[f].type == "E-3A" or flight[f].type == "F-15C" or flight[f].type == "F-15E" or flight[f].type == "F-16C bl.52d"
          or flight[f].type == "FA-18C_hornet" or flight[f].type == "F/A-18C" then
              local task_entry = {
                  ["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
                  ["auto"] = true,
                  ["id"] = "WrappedAction",
                  ["enabled"] = true,
                  ["params"] =
                  {
                      ["action"] =
                      {
                          ["id"] = "EPLRS",
                          ["params"] =
                          {
                              ["value"] = true,
                              ["groupId"] = 1,
                          }, -- end of ["params"]
                      }, -- end of ["action"]
                  },
              }
			table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
            end
        end 
					
					--attack tasks
					if (flight[f].player == true and flight[f].route[w].id == "IP") or flight[f].route[w].id == "Attack" then	--Attack waypoint for AI or IP for player
						if flight[f].task == "Strike" and flight[f].target.class == nil then									--Tasks against scenery objects with multiple target sub-elements
							
							local target_element = {}																			--table to hold the target element number to be struck
							for e = 1, #flight[f].target.elements do															--iterate trough all target elements
								if flight[f].target.elements[e].dead ~= true then												--pick only elements that are not dead
									table.insert(target_element, e)																--add to target element table
								end
							end
							for n = 1, (f - 1) * 4 do																			--shift the order of target elements for subsequent flights in package, so that each flights starts attacking different elements (flight 1: element 1-4, flight 2: element 5-8, etc)
								table.insert(target_element, target_element[1])													--shift element order, copy first element to back
								table.remove(target_element, 1)																	--delete first element
							end
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomMapObjectAttack
							-----------------------------------------------------------------------
							for n,e in ipairs(target_element) do
								local task_entry = {
									["enabled"] = false,
									["auto"] = false,
									["id"] = "AttackMapObject",
									["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
									["params"] = {
										["x"] = flight[f].target.elements[e].x,
										["y"] = flight[f].target.elements[e].y,
										["weaponType"] = weaponType,
										["expend"] = flight[f].loadout.expend,
										["direction"] = 0,
										["attackQtyLimit"] = false,
										["attackQty"] = 1,
										["directionEnabled"] = false,
										["groupAttack"] = true,
										["altitude"] = 2000,
										["altitudeEnabled"] = false,
									},
								}
								table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
							-----------------------------------------------------------------------
							
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local tgtlist = ""																					--list of of names of all target elements
							for n,e in ipairs(target_element) do
								tgtlist = tgtlist .. '{ x = ' .. flight[f].target.elements[e].x .. ', y = ' .. flight[f].target.elements[e].y .. '}, '
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomMapObjectAttack("' .. grpname .. '", {' .. tgtlist .. '}, "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '")',	--this is a custom written task to allow all aircraft in flight to attack multiple static objects simultenously
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Strike" and flight[f].target.class == "vehicle" then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "AttackGroup",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["groupId"] = flight[f].target.groupId,
									["weaponType"] = weaponType,
									["expend"] = flight[f].loadout.expend,
									["attackType"] = flight[f].loadout.attackType,
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Strike" and flight[f].target.class == "static" then
							
							local target_element = {}																			--table to hold the target element number to be struck
							for e = 1, #flight[f].target.elements do															--iterate trough all target elements
								if flight[f].target.elements[e].dead ~= true then												--pick only elements that are not dead
									table.insert(target_element, e)																--add to target element table
								end
							end
							for n = 1, (f - 1) * 4 do																			--shift the order of target elements for subsequent flights in package, so that each flights starts attacking different elements (flight 1: element 1-4, flight 2: element 5-8, etc)
								table.insert(target_element, target_element[1])													--shift element order, copy first element to back
								table.remove(target_element, 1)																	--delete first element
							end
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomStaticAttack
							-----------------------------------------------------------------------
							for n,e in ipairs(target_element) do
								local task_entry = {
									["enabled"] = false,
									["auto"] = false,
									["id"] = "AttackGroup",
									["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
									["params"] = {
										["groupId"] = flight[f].target.elements[e].groupId,
										["weaponType"] = weaponType,
										["expend"] = flight[f].loadout.expend,
									},
								}
								table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							end
							-----------------------------------------------------------------------
						
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local tgtlist = ""																					--list of of names of all target elements
							for n,e in ipairs(target_element) do
								tgtlist = tgtlist .. '"' .. flight[f].target.elements[e].name .. '", '
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomStaticAttack("' .. grpname .. '", {' .. tgtlist .. '}, "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '")',	--this is a custom written task to allow all aircraft in flight to attack multiple static objects simultenously
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Strike" and flight[f].target.class == "airbase" then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "EngageTargetsInZone",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["targetTypes"] = 
									{
										[1] = "Air",
									},
									["x"] = flight[f].target.x,
									["y"] = flight[f].target.y,
									["priority"] = 0,
									["zoneRadius"] = 3000,
									["weaponType"] = weaponType,
									["expend"] = flight[f].loadout.expend,
									["attackType"] = flight[f].loadout.attackType,
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Anti-ship Strike" then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "AttackGroup",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["groupId"] = flight[f].target.groupId,
									["weaponType"] = weaponType,
									["expend"] = flight[f].loadout.expend,
									["attackType"] = flight[f].loadout.attackType,
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							
						elseif flight[f].task == "Flare Illumination" then
							
							--this is only to display attack markers in mission editor, task will be replaced in game by CustomStaticAttack
							-----------------------------------------------------------------------
							local task_entry = {
								["enabled"] = false,
								["auto"] = false,
								["id"] = "Bombing",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = {
									["x"] = flight[f].target.x,
									["y"] = flight[f].target.y,
									["direction"] = 0,
									["attackQtyLimit"] = false,
									["attackQty"] = 1,
									["expend"] = flight[f].loadout.expend,
									["altitude"] = 1524,
									["directionEnabled"] = false,
									["groupAttack"] = true,
									["altitudeEdited"] = true,
									["altitudeEnabled"] = true,
									["weaponType"] = weaponType,
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
							-----------------------------------------------------------------------
						
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local expend = flight[f].loadout.expend
							local attackType = flight[f].loadout.attackType or "nil"
							local tgtx = "n/a"																					--target coordinate n/a, custom attach script will determine latest target position at time of attack during the misssion
							local tgty = "n/a"																					--target coordinate n/a, custom attach script will determine latest target position at time of attack during the misssion
							if flight[f].target.class ~= "vehicle" then															--if target is not a vehicle or ship, then known target coordinates are used
								tgtx = flight[f].target.x																		--use known target coordinates
								tgty = flight[f].target.y																		--use known target coordinates
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomFlareAttack("' .. grpname .. '", "' .. tgtx .. '", "' .. tgty .. '", "' .. flight[f].target.name .. '", "' .. expend .. '", "' .. weaponType .. '", "' .. attackType .. '")',	--this is a custom written task to allow coordinates bombing of target poistion at time of attack
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						
						elseif flight[f].task == "Laser Illumination" then
							local grpname = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f
							local LaserCode1 = math.random(1,8)
							local LaserCode2 = math.random(1,8)
							local LaserCode3 = math.random(1,8)
							flight[f].target.LaserCode = tonumber("1" .. LaserCode1 .. LaserCode2 .. LaserCode3)				--store laser code for flight target
							for ff = 1, #pack[p].main do																		--iterate through all main body flights
								pack[p].main[ff].target.LaserCode = tonumber("1" .. LaserCode1 .. LaserCode2 .. LaserCode3)		--store laser code in all main body flights
							end
							
							local tgt = ""
							local class
							if flight[f].target.class == "static" then
								class = "static"
								for e = 1, #flight[f].target.elements do
									tgt = tgt .. '"' .. flight[f].target.elements[e].name .. '", '
								end
							elseif flight[f].target.class == "vehicle" then
								class = "vehicle"
								tgt = flight[f].target.name
							elseif flight[f].target.class == "airbase" then
							
							else
								class = "scenery"
								for e = 1, #flight[f].target.elements do
									tgt = tgt .. '{ x = ' .. flight[f].target.elements[e].x .. ', y = ' .. flight[f].target.elements[e].y .. '}, '
								end
							end
							
							local task_entry = {																				--task is a command to run LUA code
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Script",
										["params"] = 
										{
											["command"] = 'CustomLaserDesignation("' .. grpname .. '", "' .. tgt .. '", "' .. class .. '", "' .. flight[f].target.LaserCode .. '")',	--this is a custom written task to allow coordinates bombing of target poistion at time of attack
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						
						end
					end
					
					--SEAD engage tasks for each route segment
					if flight[f].task == "SEAD" then
						if flight[f].route[w].SEAD_radius then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "ControlledTask",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["task"] = 
									{
										["id"] = "EngageTargets",
										["params"] = 
										{
											["targetTypes"] = 
											{
												[1] = "SAM TR",
												[2] = "MR SAM",
												[3] = "LR SAM",
											},
											["maxDistEnabled"] = true,
											["priority"] = 0,
											["maxDist"] = flight[f].route[w].SEAD_radius,
											["weaponType"] = 268402702,
										},
									},
									["stopCondition"] = 
									{
										["lastWaypoint"] = w,
									},
								}
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--orbit on departure
					if flight[f].route[w].id == "Departure" and flight[f].task ~= "Transport" then
					
--                if flight[f].helicopter == true then
--                  temp_altitude = waypoints[w]["alt"] + 20                                -- Mod M06 helicoptere              
--                else
--                  temp_altitude =  waypoints[w]["alt"] + (Pn - 1) * 152.4                 --each subseqent flight in package orbits 500ft higher               
--                end
                    
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "ControlledTask",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["task"] = 
								{
									["id"] = "Orbit",
									["params"] = 
									{
								  	["altitude"] =  waypoints[w]["alt"] + (Pn - 1) * 152.4,									--each subseqent flight in package orbits 500ft higher
										["pattern"] = "Circle",
										["speed"] = pack[p].main[1].loadout.vCruise / 3 * 2,
									},
								},
								["stopCondition"] = 
								{
									["time"] = departure_time
								}
							}
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--orbit on station
					if flight[f].route[w].id == "Station" and flight[f].route[w + 1].id == "Station" then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "ControlledTask",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["task"] = 
								{
									["id"] = "Orbit",
									["params"] = 
									{
										["altitude"] = flight[f].loadout.hAttack,
										["pattern"] = "Race-Track",
										["speed"] = flight[f].loadout.vAttack,
									},
								},
								["stopCondition"] = 
								{
									["time"] = flight[f].route[w + 1].eta
								}
							}
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--orbit on egress
					if flight[f].route[w].id == "Egress" and (flight[f].task == "SEAD" or flight[f].task == "Escort") then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "ControlledTask",
							["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["task"] = 
								{
									["id"] = "Orbit",
									["params"] = 
									{
										["altitude"] = waypoints[w]["alt"],
										["pattern"] = "Circle",
										["speed"] = pack[p].main[1].loadout.vCruise,
									},
								},
								["stopCondition"] = 
								{
									["time"] = flight[f].route[w].eta
								}
							}
						}
						table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
					end
					
					--restrict RTB on winchester from IP on
					if flight[f].route[w].id == "IP" and (flight[f].task == "SEAD" or flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination") then
						if flight[f].player ~= true then
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = 0,
											["name"] = 10,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--restrict weapon jettison from IP on
					if flight[f].route[w].id == "IP" and (flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination") then
						if flight[f].player ~= true then	
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = true,
											["name"] = 15,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--allow weapon jettison from egress on
					if flight[f].route[w].id == "Egress" and (flight[f].task == "SEAD" or flight[f].task == "Strike" or flight[f].task == "Anti-ship Strike" or flight[f].task == "Flare Illumination" or flight[f].task == "Laser Illumination") then
						if flight[f].player ~= true then	
							local task_entry = {
								["enabled"] = true,
								["auto"] = false,
								["id"] = "WrappedAction",
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = false,
											["name"] = 15,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--IP/egress reaction on threat for recon
					if flight[f].task == "Reconnaissance" and flight[f].route[w].id == "IP" then
						if flight[f].player ~= true then	
							local task_entry = {
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["auto"] = false,
								["id"] = "WrappedAction",
								["enabled"] = true,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = 1,
											["name"] = 1,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					elseif flight[f].task == "Reconnaissance" and flight[f].route[w].id == "Egress" then
						if flight[f].player ~= true then	
							local task_entry = {
								["number"] = #waypoints[w]["task"]["params"]["tasks"] + 1,
								["auto"] = false,
								["id"] = "WrappedAction",
								["enabled"] = true,
								["params"] = 
								{
									["action"] = 
									{
										["id"] = "Option",
										["params"] = 
										{
											["value"] = 2,
											["name"] = 1,
										},
									},
								},
							}
							table.insert(waypoints[w]["task"]["params"]["tasks"], task_entry)
						end
					end
					
					--navigation information on waypoint name for player flight
					if flight[f].player then																				--flight is player flight
						if waypoints[w - 1] then																			--previous waypoint exists
							local distance = GetDistance(waypoints[w - 1], waypoints[w])									--distance between waypoints
							if waypoints[w].name == "Target" then
								distance = GetDistance(waypoints[w - 2], waypoints[w])										--for target waypoint measure distance from IP, since attack point is removed for player flight
							end
							if distance > 0 then																			--distance is not zero
								local heading = math.floor(GetHeading(waypoints[w - 1], waypoints[w]))						--heading between waypoints
								heading = heading - camp.variation															--adjust heading (true heading) with variation of map to get magnetix heading
								if heading < 0 then
									heading = heading + 360
								elseif heading > 359 then
									heading = heading - 360
								end
								if heading < 10 then
									heading = "00" .. heading
								elseif heading < 100 then
									heading = "0" .. heading
								end
								if camp.units == "metric" then
									distance = math.ceil(distance / 1000) .. "KM"
								else
									distance = math.ceil(distance / 1000 * 0.539957) .. "NM"
								end
								
								waypoints[w]["name"] = waypoints[w]["name"] .. ": " .. heading .. "/" .. distance			--add heading and distance to waypoint name
							end
						end
					end
				end
				
				--lock ETA and speed of first waypoint
				waypoints[1]["ETA_locked"] = true
				waypoints[1]["speed_locked"] = true
				if waypoints[1]["speed"] == nil then
					waypoints[1]["speed"] = 1
				end
				
				--remove attack WP for player flight
				if flight[f].player == true then
					for w = 1, #waypoints do
						if waypoints[w].briefing_name == "Attack" then
							table.remove(waypoints, w)
							camp.player.tgt_wp = camp.player.tgt_wp - 1
							break
						end
					end
				end
				
				--store player waypoints for briefing creation
				if flight[f].player == true then
					camp.player.waypoints = deepcopy(waypoints)
					if #waypoints > 1 then
						camp.player.waypoints[2].speed = 0
						camp.player.waypoints[2].alt = 0
					end
					if #waypoints > 2 then
						camp.player.waypoints[3].speed = pack[p].main[1].loadout.vCruise / 4 * 3
					end
				end
				
				--remove target WP for certain flights
				if target_wp_remove then
					table.remove(waypoints, target_wp_remove)
				end
				
				--remove taxi waypoint ****** WHAT???? (Miguel interrogation .. :) )
				if waypoints[1].name == "Taxi" then			 
					table.remove(waypoints, 1)
             
				  waypoints[1]["name"] = "Departure"

					-- Miguel21 Mod M6 type helicoptere and hotstart 
					if  hotstart[flight[f].type]   then 
					   waypoints[1]["action"] = hotstart[flight[f].type]["action"]
					   waypoints[1]["type"] = hotstart[flight[f].type]["type"]
					end

					if flight[f].airdromeId > 40 then
						waypoints[1]["linkUnit"] = flight[f].airdromeId
						waypoints[1]["helipadId"] = flight[f].airdromeId
					else
						waypoints[1]["airdromeId"] = flight[f].airdromeId
					end
					waypoints[1]["ETA"] = spawn_time
					waypoints[1]["ETA_locked"] = true
					waypoints[1]["speed_locked"] = true
					if waypoints[1]["speed"] == nil then
						waypoints[1]["speed"] = 1
					end
				end
				
				--first waypoint RTB on winchester
				--disabled due to AI problems (AI will ignore all threats once in RTB mode)
				--[[if flight[f].task == "SEAD" or flight[f].task == "CAS" or flight[f].task == "Ground Attack" or flight[f].task == "Pinpoint Strike" or flight[f].task == "Runway Attack" or flight[f].task == "Anti-ship Strike" then
					if flight[f].player ~= true then
						local task_entry = {
							["enabled"] = true,
							["auto"] = false,
							["id"] = "WrappedAction",
							["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
							["params"] = 
							{
								["action"] = 
								{
									["id"] = "Option",
									["params"] = 
									{
										["value"] = weaponType,
										["name"] = 10,
									},
								},
							},
						}
						table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
					end
				]]--end
				
				--first waypoint reaction to threat
				local task_entry = {
					["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
					["auto"] = false,
					["id"] = "WrappedAction",
					["enabled"] = true,
					["params"] = 
					{
						["action"] = 
						{
							["id"] = "Option",
							["params"] = 
							{
								["value"] = 2,
								["name"] = 1,
							},
						},
					},
				}
				table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				
				--first waypoint restrict jettison for SEAD
				if flight[f].task == "SEAD" then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "WrappedAction",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["action"] = 
							{
								["id"] = "Option",
								["params"] = 
								{
									["value"] = true,
									["name"] = 15,
								},
							},
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				end
				
				--first waypoint restrict air-air
				if flight[f].loadout.restrict_aa then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "WrappedAction",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["action"] = 
							{
								["id"] = "Option",
								["params"] = 
								{
									["value"] = true,
									["name"] = 14,
								},
							},
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				end
				
				--first waypoint enroute tasks
				if flight[f].task == "CAP" then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "EngageTargets",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["targetTypes"] = 
							{
								[1] = "Planes",
							},
							["maxDistEnabled"] = true,
							["priority"] = 0,
							["maxDist"] = flight[f].loadout.standoff,
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)							
				elseif flight[f].task == "Fighter Sweep" then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "EngageTargets",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["targetTypes"] = 
							{
								[1] = "Planes",
							},
							["maxDistEnabled"] = true,
							["priority"] = 0,
							["maxDist"] = flight[f].loadout.standoff,
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)	
				elseif flight[f].task == "Escort" and flight[f].helicopter ~= true then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "EngageTargets",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
							["targetTypes"] = 
							{
								[1] = "Fighters",
							},
							["maxDistEnabled"] = true,
							["priority"] = 0,
							["maxDist"] = flight[f].loadout.standoff,
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
-- modif Miguel21 M06 : helicoptere playable
        elseif flight[f].task == "Escort" and flight[f].helicopter == true then
          local task_entry = {
            ["enabled"] = true,
            ["auto"] = false,
            ["id"] = "EngageTargets",
            ["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
            ["params"] = 
            {
              ["targetTypes"] = 
              {
                  [1] = "Helicopters",
                  [2] = "Ground Units",
                  [3] = "Light armed ships",
              },
              ["maxDistEnabled"] = true,
              ["priority"] = 0,
              ["maxDist"] = flight[f].loadout.standoff,
            },
          }
          table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				elseif flight[f].task == "AWACS" then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "AWACS",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
				elseif flight[f].task == "Refueling" then
					local task_entry = {
						["enabled"] = true,
						["auto"] = false,
						["id"] = "Tanker",
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["params"] = 
						{
						},
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
					
                    
                -- local tempCallSign = GetCallsign(flight[f].country, f, 1, flight[f].task)
				
				local tempTACAN = GetTacanChannel(side, p , f, 1)
                
					local task_entry = {
						["number"] = #waypoints[1]["task"]["params"]["tasks"] + 1,
						["auto"] = true,
						["id"] = "WrappedAction",
						["enabled"] = true,
						["params"] = 
						{
							["action"] = 
							{
								["id"] = "ActivateBeacon",
								["params"] = 
								{
									["type"] = 4,
									["AA"] = true,
									["unitId"] = GetUnitId(  flight[f].country, flight[f].type, p, role, f, 1),
									-- ["unitId"] = GetUnitId(tempCallSign),
									["callsign"] = "TKR",
									["modeChannel"] = "X",
									["name"] = "",
									-- ["channel"] = GetTacanChannel(side, p , f, 1),					-- (MIGUEL21)
									["channel"] = tempTACAN,
									["system"] = 4,
									["bearing"] = true,
									["frequency"] = (tempTACAN + 1087) *1000000, --1101000000,
								}, -- end of ["params"]
							}, -- end of ["action"]
						}, -- end of ["params"]
					}
					table.insert(waypoints[1]["task"]["params"]["tasks"], task_entry)
					

					ATO[side][p][role][f].channel = package_channel[side][p][f][1]							-- Miguel21 modificaiton TACAN briefing
				end
					
				----- define units -----
				local units = {}
					-- Miguel21 modification Multijoueur M11
					if ( coopFlag01  and flight[f].player ) then
						if flight[f].number < coop then
							flight[f].number = coop
						end	
						flight[f].multi1 = true						
					elseif ( coopFlag02  and   flight[f].client2  ) then		-- si le type d'avion N°2 ET s'il décolle avant 15mn
						if flight[f].number < coop_flight2 then
							flight[f].number = coop_flight2
						end	
						flight[f].multi2 = true
					end

					for n = 1, flight[f].number do
					
						-- Modification Miguel21 Skill M12
						if n == 1 then                                           -- le Leader est en général plus experimenté
							if math.random(1, 100) >= 95 then                      -- 5 % de chance d'etre excellent
							  nskill = 4
							else						  	
								  nskill = skillWish + math.random(-1, 1)
						    end
						else 
							nskill =  skillWish + math.random(-2, 1)
						end
						
						if nskill < 1 then nskill = 1
						elseif nskill > 4 then nskill = 4
						else nskill = nskill
						end
				 
					units[n] = {
						["alt"] = waypoints[1].alt,
						["heading"] = 0,
						["callsign"] = GetCallsign(flight[f].country, f, n, flight[f].task),
						["psi"] = 0,
						["livery_id"] = flight[f].livery,
						["onboard_num"] = "0" .. math.random(1, 99),
						["type"] = flight[f].type,
						["y"] = waypoints[1]["y"] + ((n - 1) * 100),
						["x"] = waypoints[1]["x"] + ((n - 1) * 100),
						["name"] = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f .. "-" .. n,
						["payload"] = flight[f].loadout.stores,
						["speed"] = waypoints[1].speed,
						["unitId"] = GetUnitId(  flight[f].country, flight[f].type, p, role, f,n), -- GenerateID(),			Miguel InitId
						["alt_type"] = waypoints[1].alt_type,
						["skill"] = flight[f].skill,
						["hardpoint_racks"] = true,
						["skill"] = skillTab[nskill],
					}
					
					--multiple skins for aircraft
					if type(units[n]["livery_id"]) == "table" then												--if skin is a table
						units[n]["livery_id"] = units[n]["livery_id"][math.random(1, #units[n]["livery_id"])]	--chose a random skin from table
					end
				end
				
			--["lateActivation"] = GetActivation( flight[f]),	
				----- define group -----
				local group = {
					-- ["lateActivation"] = GetActivation( flight[f]),									--Miguel21 modification M08.e
					['frequency'] = GetFrequency(side, p, flight[f].helicopter),
					['taskSelected'] = true,
					['modulation'] = 0,
					['groupId'] = GenerateID(),
					['tasks'] = {
					},
					['route'] = {
						['points'] = waypoints,
					},
					['hidden'] = true,
					['units'] = units,
					['radioSet'] = true,
					["name"] = "Pack " .. p .. " - " .. flight[f].name .. " - " .. flight[f].task .. " " .. f,
					['communication'] = true,
					['x'] = waypoints[1]["x"],
					['y'] = waypoints[1]["y"],
					['start_time'] = GetStartTime( flight[f]),
					['task'] = flight[f].task,
					['uncontrolled'] = false,
				--	['channel'] = GetTacanChannel(side, p),
				}
				
				if flight[f].task == "Escort" then												--if task is escort
					group['task'] = "Fighter Sweep"												--make task fighter sweep, because escort does not have engage tasks
				elseif flight[f].task == "Strike" then											--Strike is a generic A-G task that needs to be replaced by the respective DCS task
					if flight[f].target.class == nil then
						group['task'] = "Ground Attack"
					elseif flight[f].target.class == "vehicle" then
						group['task'] = "CAS"
					elseif flight[f].target.class == "static" then
						group['task'] = "CAS"
					elseif flight[f].target.class == "airbase" then
						group['task'] = "CAS"
					end
				elseif flight[f].task == "Escort Jammer" then									--Escort Jammer task does not exitsts in DCS and needs to be replaced
					group['task'] = "Ground Attack"
				elseif flight[f].task == "Flare Illumination" then								--Flare illumination task does not exist in DCS and needs to be replaced
					group['task'] = "Ground Attack"
				elseif flight[f].task == "Laser Illumination" then								--Laser illumination task does not exist in DCS and needs to be replaced
					group['task'] = "AFAC"
				end
				
				if camp.player and camp.player.pack_n == p and camp.player.EWR_freq then		--player package and player has an EWR frequency (site that detected targets to intercept)
					group['frequency'] = tonumber(camp.player.EWR_freq)							--put player package on EWR frequency
				end
				
				---- unhide player package -----
				if camp.debug then																--debug is on
					group.hidden = false														--unhide all groups
				elseif camp.player and camp.player.side == side then							--player side										
					if camp.player.pack_n == p then												--package is player package
						group.hidden = false													--unhide group
					elseif flight[f].task == "AWACS" then										--flight is an AWACS on player side
						group.hidden = false													--unhide group
					elseif flight[f].task == "Refueling" then									--flight is a tanker on player side
						group.hidden = false													--unhide group
					end
				end
				
				----- late groups spawn uncontrolled at mission start -----
				-- -- modif Miguel M03.c : apparition décalé sur PA
				if group['route']['points'][1]["ETA"] > 0 and flight[f].task ~= "Intercept"		--group launches after mission start
             and flag_4Place ~= true then
             
					group['route']['points'][1]["ETA"] = 0										--first waypoint ETA is 0 for uncontrolled group to spawn at mission start
					
					if flight[f].player ~= true then											--for non-player groups
						group['uncontrolled'] = true											--make group uncontrolled
						
						--triggered action to start uncontrolled group
						group['tasks'] = {
							[1] = {
								["number"] = 1,
								["name"] = group.name,
								["id"] = "WrappedAction",
								["auto"] = false,
								["enabled"] = true,
								["params"] = {
									["action"] = {
										["id"] = "Start",
										["params"] = {},
									},
								},
							},
						}
						
						--mission trigger to initiate triggered action
						local trig_n = #mission.trig.func + 1										--next available trigger number
						mission.trig.func[trig_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
						mission.trig.flag[trig_n] = true
						mission.trig.conditions[trig_n] = "return(c_time_after(" .. spawn_time .. ") )"
						mission.trig.actions[trig_n] = "a_set_ai_task(" .. group.groupId .. ", 1); mission.trig.func[" .. trig_n .. "]=nil;"
						mission.trigrules[trig_n] = {
							['rules'] = {
								[1] = {
									["seconds"] = spawn_time,
									["coalitionlist"] = "red",
									["predicate"] = "c_time_after",
									["zone"] = "",
								},
							},
							['eventlist'] = '',
							['comment'] = 'Trigger ' .. trig_n,
							['predicate'] = 'triggerOnce',
							['actions'] = {
								[1] = {
									["ai_task"] = {
										[1] = "",
										[2] = "",
									},
									["predicate"] = "a_set_ai_task",
									["set_ai_task"] = {
										[1] = group.groupId,
										[2] = 1,
									}
								},
							},
						}
					end
				end
				
				
				----- provisions for interceptors/GCI/AWACS -----
				if flight[f].task == "Intercept" and flight[f].player ~= true then
					group['uncontrolled'] = true												--make interceptor groups uncontrolled at mission start
					
					GCI.Flag = GCI.Flag + 1														--go to next trigger flag number
					
					--build Interceptor table
					GCI.Interceptor[side].ready[group.name] = {
						number = #group.units,
						range = flight[f].target.radius,
						x = group.x,
						y = group.y,
						flag = GCI.Flag,
						tot_from = flight[f].tot_from,
						tot_to = flight[f].tot_to,
						airdromeId = flight[f].airdromeId,
					}
					
					--triggered action to start uncontrolled group
					group['tasks'] = {
						[1] = {
							["number"] = 1,
							["name"] = group.name,
							["id"] = "WrappedAction",
							["auto"] = false,
							["enabled"] = true,
							["params"] = {
								["action"] = {
									["id"] = "Start",
									["params"] = {},
								},
							},
						},
					}
					
					--mission trigger to initiate triggered action
					local trig_n = #mission.trig.func + 1										--next available trigger number
					mission.trig.func[trig_n] = "if mission.trig.conditions[" .. trig_n .. "]() then mission.trig.actions[" .. trig_n .. "]() end"
					mission.trig.flag[trig_n] = true
					mission.trig.conditions[trig_n] = "return(c_flag_is_true(" .. GCI.Flag .. ") )"
					
					-- --Miguel21 modification M08.f si intercepteur sur CVN, on active le group qui est en attente, il n'est pas sur le CVN
					if flag_4Place == true then 
						mission.trig.actions[trig_n] = "a_activate_group(" .. group.groupId .. "); mission.trig.func[" .. trig_n .. "]=nil;"
						mission.trigrules[trig_n] = {
							['rules'] = {
								[1] = {
									["flag"] = GCI.Flag,
									["coalitionlist"] = "red",
									["predicate"] = "c_flag_is_true",
									["zone"] = "",
								},
							},
							['eventlist'] = '',
							['comment'] = 'Trigger ' .. trig_n,
							['predicate'] = 'triggerOnce',
							['actions'] = {
								[1] = {
									["group"] = group.groupId,
									["ai_task"] = {
										[1] = "",
										[2] = "",
									},
									["predicate"] = "a_activate_group",
									["set_ai_task"] = {
										[1] = group.groupId,
										[2] = 1,
									}
								},
							},
						}
					else
						mission.trig.actions[trig_n] = "a_set_ai_task(" .. group.groupId .. ", 1); mission.trig.func[" .. trig_n .. "]=nil;"
						mission.trigrules[trig_n] = {
							['rules'] = {
								[1] = {
									["flag"] = GCI.Flag,
									["coalitionlist"] = "red",
									["predicate"] = "c_flag_is_true",
									["zone"] = "",
								},
							},
							['eventlist'] = '',
							['comment'] = 'Trigger ' .. trig_n,
							['predicate'] = 'triggerOnce',
							['actions'] = {
								[1] = {
									["ai_task"] = {
										[1] = "",
										[2] = "",
									},
									["predicate"] = "a_set_ai_task",
									["set_ai_task"] = {
										[1] = group.groupId,
										[2] = 1,
									}
								},
							},
						}
					end
				elseif flight[f].task == "AWACS" then
					GCI.EWR[side][units[1].name] = true											--add AWACS to EWR table
				end

				--Miguel21 modification M03.c :  Apparition décalé sur PA
				-- SinglePlayer: fait partir "seulement" les IA sur catapulte
				if (flight[f].type == 'F-14B' or flight[f].type == 'FA-18C_hornet' or flight[f].type == 'E-2C' or flight[f].type == 'S-3B Tanker') and flight[f].player ~= true and flag_4Place == true then
					 ETA_minute =  math.floor(waypoints[1].ETA /60)
					if not placePA[flight[f].base] then placePA[flight[f].base] = {} end					
					
					-- les intercepteurs IA, sur CVN,  commencent en vol
					if 	flight[f].task == "Intercept"  then 
						waypoints[1]["action"] = "Turning Point"
						waypoints[1]["type"] = "Turning Point"
						waypoints[1]["alt"] = 250
						waypoints[1]["speed"] = 250
						waypoints[1]["speed_locked"] = false
						waypoints[1]["ETA"] =  86400 							-- waypoints[1]["ETA"]  -- lateActivation: si 1 jour day , ajouter: (86400 +) Miguel21 modification M08.e
					
						
							-- ["linkUnit"] = 830,
							-- ["helipadId"] = 830,
						-- enleve le lien du CVN pour les appareils commençant en vol
						-- Miguel21 modification M08.g
						for iw , wpt in pairs(waypoints) do
							for it, chapt in pairs(wpt)  do 
								if it == "linkUnit" or it == "helipadId" then
								 waypoints[iw][it] = nil	
								end
							end 
						end
						
						--Miguel21 modification M08.f, décale l'apparition des intercepteurs en vol, risque de collision	
						if not pack[p] then	pack[p] = {} end
						if not pack[p][Pn] then
							pack[p][Pn] = {}
				-- print("AltAvant"..waypoints[1]["alt"])
							deltaH = deltaH +1 
							waypoints[1]["alt"] = waypoints[1]["alt"] + 50 * deltaH
							randX = math.random(-1500, 500)
							randY = math.random(-1500, 500)
							waypoints[1]["x"] = waypoints[1]["x"] + randX
							waypoints[1]["y"] = waypoints[1]["y"] + randY
				-- print("AltApres"..waypoints[1]["alt"])
						end
						for ii = 1, #units do
							units[ii]["alt"] = waypoints[1]["alt"]
							units[ii]["speed"] = 250
							-- units[ii]["start_time"] = 86400						-- waypoints[1]["ETA"] Miguel21 modification M08.e
							units[ii]["x"] = units[ii]["x"] + randX
							units[ii]["y"] = units[ii]["y"] + randY
						end
					else
						waypoints[1]["action"] = "From Runway"						-- depart sur catapult obligatoir
						waypoints[1]["type"] = "TakeOff"
						units[1]["parking"] = 1
						units[1]["parking_id"] = 1
						if units[2] then
							units[2]["parking"] = 2
							units[2]["parking_id"] = 2	
						end
						if units[3] then
							units[3]["parking"] = 3
							units[3]["parking_id"] = 3
						end
						if units[4] then
							units[4]["parking"] = 4
							units[4]["parking_id"] = 4
						end
						
						etiquette = "Pack " .. p .. " - "..flight[f].type.." - ".. flight[f].name .. " - " .. flight[f].task
						if  waypoints[1].ETA - 180	 > 0 then						-- apparition 180s avant departure		
							if not	placePA[flight[f].base][ETA_minute - 3]  then 		 -- check si un avion a reservé la catapulte
							-- la catapulte est libre et on lui assigne 3 mn
								placePA[flight[f].base][ETA_minute -3 ] = etiquette
								placePA[flight[f].base][ETA_minute -2 ] = etiquette
								placePA[flight[f].base][ETA_minute -1 ] = etiquette
								waypoints[1].ETA = waypoints[1].ETA - 180	
							else 	
								for i = ETA_minute -3, 0, -1  do							-- cherche un creneau horaire catapulte libre
									if not	placePA[flight[f].base][i]  then 		-- on a trouvé un creneau de 3mn et on lui assigne
										placePA[flight[f].base][i] = etiquette 
										placePA[flight[f].base][i-1] = etiquette
										placePA[flight[f].base][i-2] = etiquette
										waypoints[1].ETA = waypoints[1].ETA - (i *60)
										break
									end -- if										
								end -- for
							end -- if else
						else
							-- cas d'apparition entre 0 et 3mn
							if 	not placePA[flight[f].base][ETA_minute] then
									placePA[flight[f].base][ETA_minute +2 ] = etiquette
									placePA[flight[f].base][ETA_minute +1] = etiquette
									placePA[flight[f].base][ETA_minute] = etiquette	
								-- print(flight[f].base.." Catapult: Time slot assigned at : "..FormatTime(camp.time+waypoints[1].ETA, "hh:mm") .." for ".. units[1].callsign.name)	
							else
								-- aucune place dispo, ce flight commence en vol
								waypoints[1]["action"] = "Turning Point"
								waypoints[1]["type"] = "Turning Point"
							end
						end
					end	--if intercepteur	
				end -- if F-14B' or flight[f].type == 'FA-18C_hornet
				
				-- AI pur, SinglePlayer, 1 Flight  de 4 AI F-14 commence sur catapult
				-- if flight[f].type == 'F-14B'  and flight[f].player ~= true and flight[f].number >= 2 and coopFlag01 ~= true 
					-- and string.find(flight[f].base,"CVN") and waypoints[1]["type"] ~= "Turning Point" then
					-- waypoints[1]["action"] = "From Runway"
					-- waypoints[1]["type"] = "TakeOff"
				-- end
				-- Player Flight : SinglePlayer, si 4 F-14, on le force à 2 pour éviter les collisions
				if flight[f].type == 'F-14B'  and flight[f].player == true and flight[f].number >= 2 and coopFlag01 ~= true and string.find(flight[f].base,"CVN") then
					flight[f].number = 2
					table.remove(units, 3)
					table.remove(units, 4)
				end
				
				
				-- --AI pure, SinglePlayer, f14+f18 Intercept commencent sur catapult (sauf ceux qui commence déjà en l'air)
				-- if(flight[f].type == 'F-14B' or flight[f].type == 'FA-18C_hornet')  and flight[f].player ~= true and flight[f].task == "Intercept"
					-- and coopFlag01 ~= true and string.find(flight[f].base,"CVN") and waypoints[1]["type"] ~= "Turning Point"then
					-- waypoints[1]["action"] = "From Runway"
					-- waypoints[1]["type"] = "TakeOff"
				-- end
				
				-- si multijoueur, les Flight AI commencent en vol
				if (flight[f].type == 'F-14B' or flight[f].type == 'FA-18C_hornet') 	and coopFlag01	and flight[f].player ~= true and string.find(flight[f].base,"CVN") then
					waypoints[1]["action"] = "Turning Point"
					waypoints[1]["type"] = "Turning Point"
				end
				
				

				
				if flight[f].player == true then												--if this is the player flight

-- modif Miguel M03 : Parking assigné des AV8 sur LHA
					--Miguel : cherche le pays du LHA
					side_LHA = false
					for c = 1, #mission.coalition[side].country do
						if mission.coalition[side].country[c].name == flight[f].country then
							side_LHA = c
							break 
						end
					end

					--Miguel : cherche si le LHA est present dans la mission, si oui, on assigne les numero de parking avec le joueur en dernier
					LHA = false
					if mission.coalition[side].country[side_LHA].ship then                         --mod gazelle
						for i= 1, #mission.coalition[side].country[side_LHA].ship.group do
							for j= 1, #mission.coalition[side].country[side_LHA].ship.group[i].units do
								 if mission.coalition[side].country[side_LHA].ship.group[i].units[j]['type'] == 'LHA_Tarawa' then
									 LHA = true
									 break
								 end 
							 end
						 end
					end
					
					if flight[f].type == 'AV8BNA' and  LHA == true then
						for i = 1, flight[f].number  do											-- Miguel21 : place les AV8 correctement sur le porte aeronef, avec le player en dernier
							units[i]["parking"] = flight[f].number +1 - i
							units[i]["parking_id"] = flight[f].number +1 - i
						end
					end
					

	
					if coop == 1 then
						units[1]["skill"] = "Player"											--make first aircraft in flight the player aircraft
						packagePlayer = p
						if coopFlag01 then
							units[1]["skill"] = "Client"
							MultiPlayerFlight1 = true
							packagePlayer = p
						end
	
					elseif coop == 2 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						MultiPlayerFlight1 = true
						packagePlayer = p
					elseif coop == 3 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
						MultiPlayerFlight1 = true
						packagePlayer = p
					elseif coop == 4 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
						units[4]["skill"] = "Client"
						MultiPlayerFlight1 = true
						packagePlayer = p
					end
				-- end
				
				-- Miguel21 modification M11 : Multiplayer
				elseif flight[f].multi2   then							-- si le type d'avion N°2 ET s'il décolle avant 15mn
					MultiPlayerFlight2 = true
						waypoints[1].ETA = 0						-- Place l'heure d'apparition au lancement de mission, pour avoir plus de temps...^^	
					if coop_flight2 == 1 then
						units[1]["skill"] = "Client"
					elseif coop_flight2 == 2 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
					elseif coop_flight2 == 3 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
					elseif coop_flight2 == 4 then
						units[1]["skill"] = "Client"
						units[2]["skill"] = "Client"
						units[3]["skill"] = "Client"
						units[4]["skill"] = "Client"
					end
				end
				
				
				
				if type(units[1].callsign) == "number" then										--Russian style
					ATO[side][p][role][f].callsign = units[1].callsign							--store flight callsign in ATO
				else																			--NATO style
					ATO[side][p][role][f].callsign = units[1].callsign.name						--store flight callsign in ATO									
				end
				



				ATO[side][p][role][f].frequency = group.frequency								--store package frequency in ATO
				
				
				------ add group to mission -----
				for c = 1, #mission.coalition[side].country do
					if mission.coalition[side].country[c].name == flight[f].country then
						if flight[f].helicopter ~= true then

							if mission.coalition[side].country[c].plane == nil then
								mission.coalition[side].country[c].plane = {
									group = {}
								}
							end
							table.insert(mission.coalition[side].country[c].plane.group, group)
							if flight[f].player == true then										
								camp.player.group = mission.coalition[side].country[c].plane.group[#mission.coalition[side].country[c].plane.group]		--store a link to the player group in mission
							end
						else
							if mission.coalition[side].country[c].helicopter == nil then


								mission.coalition[side].country[c].helicopter = {
									group = {}
								}
							end
							table.insert(mission.coalition[side].country[c].helicopter.group, group)
							if flight[f].player == true then										
								camp.player.group = mission.coalition[side].country[c].helicopter.group[#mission.coalition[side].country[c].helicopter.group]		--store a link to the player group in mission
							end
						end
					end
				end
				
-- .." "..waypoints[1].name.."  "..waypoints[1].type.."  "..waypoints[1].action.."  "

				if debugLoc then 
				  io.write("Pack: "..p.." Nb "
						.."  "..flight[f].number.."  "
						.."  "..flight[f].type
						.."  "..flight[f].task
						.."  "..flight[f].target_name
						.."  "..waypoints[1].name
						.." ETA ".. math.floor(waypoints[1].ETA)
						.." // "..units[1].skill
						)
						
					for nn = 2 , #units do
						io.write(" / ".. units[nn].skill )
					end
						
					for wp_n,wp in pairs(pack[p].main[1].route) do		
						if wp.id == "Target" or wp.id == "Station" then		
							tot = FormatTime(camp.time + wp.eta, "hh:mm:ss")				
							io.write(" / ".. tot )
						end
					end
					
					io.write("\n")
				end
			  
			end
		end
	end
end
					
print("\n\n")
if packagePlayer then
print("Schedule of the scenario: "..FormatTime(camp.time, "hh:mm"))
print("\Your Package")

	for side, _coalition in pairs(mission.coalition) do
			for c, _country in pairs(mission.coalition[side].country) do 	
				if mission.coalition[side].country[c].plane then
					if mission.coalition[side].country[c].plane.group then

						for g = 1, #mission.coalition[side].country[c].plane.group do
								client = ""
								pack = mission.coalition[side].country[c].plane.group[g].units[1]['name']
								_, _, p, p2 = string.find(pack, "Pack%s(%d+)")
								
								if tonumber(p) == packagePlayer and side == camp.player.side then
								if mission.coalition[side].country[c].plane.group[g].units[1]['skill'] == "Client" then client = " - Client " end
								if mission.coalition[side].country[c].plane.group[g].units[1]['skill'] == "Player" then client = " - Player " end
								
								  io.write(
										FormatTime(mission.coalition[side].country[c].plane.group[g].route.points[1].ETA + camp.time, "hh:mm")
									  .." "..#mission.coalition[side].country[c].plane.group[g].units
									  .." X "..mission.coalition[side].country[c].plane.group[g].units[1]['type']
									  
									  .." - "..mission.coalition[side].country[c].plane.group[g].units[1]['name']
									  .. client
									  .."\n" )
												 
								end
							-- end
						end
					end
				end
			end
	end
end
if packagePlayer then
	for side, _coalition in pairs(mission.coalition) do
			for c, _country in pairs(mission.coalition[side].country) do 	
				if mission.coalition[side].country[c].helicopter then
					if mission.coalition[side].country[c].helicopter.group then

						for g = 1, #mission.coalition[side].country[c].helicopter.group do
								client = ""
								pack = mission.coalition[side].country[c].helicopter.group[g].units[1]['name']
								_, _, p, p2 = string.find(pack, "Pack%s(%d+)")
								
								if tonumber(p) == packagePlayer and side == camp.player.side then
								if mission.coalition[side].country[c].helicopter.group[g].units[1]['skill'] == "Client" then client = " - Client " end
								if mission.coalition[side].country[c].helicopter.group[g].units[1]['skill'] == "Player" then client = " - Player " end
								
								  io.write(
										FormatTime(mission.coalition[side].country[c].helicopter.group[g].route.points[1].ETA + camp.time, "hh:mm")
									  .." "..#mission.coalition[side].country[c].helicopter.group[g].units
									  .." X "..mission.coalition[side].country[c].helicopter.group[g].units[1]['type']
									  
									  .." - "..mission.coalition[side].country[c].helicopter.group[g].units[1]['name']
									  .. client
									  .."\n" )
												 
								end
							-- end
						end
					end
				end
			end
	end
end

	-- http://www.lua.org/pil/19.3.html
	-- Trier un tableau A[b] en le classant par A, et non b... pas simple .. ^^
   function pairsByKeys (t, f)
      local a = {}
      for n in pairs(t) do table.insert(a, n) end
      table.sort(a, f)
      local i = 0      -- iterator variable
      local iter = function ()   -- iterator function
        i = i + 1
        if a[i] == nil then return nil
        else return a[i], t[a[i]]
        end
      end
      return iter
    end

-- affiche  le timing des avions sur le pont/catapulte pour prévenir le/les joueurs que des IA seront dessus
tabNam = {}	
print("\n")
if placePA then
	for base , Tmn in pairs(placePA) do	
		print(tostring(base).."Catapult: Time slot assigned at ...")
		for mn, name in pairsByKeys(Tmn) do
			
			if tabNam[name] ~= true then
				catTime = camp.time + (mn * 60)
				io.write(" "..FormatTime(catTime, "hh:mm").. " - "..tostring(name).."\n")
				tabNam[name] = true
			end
			
		end
		
	end
end


-- _affiche(package_unitId, "package_unitId")

